package com.winit.common.util;

import com.winit.common.base.bean.LoginUser;
import com.winit.common.base.bean.RoleInfo;

/**
 * 操作记录
 * Created by wangjian on 16/5/11.
 */
public class LogUtil {

    public enum OperateType {
        QA_AUTHORIZE("QA授权"),
        CALCEL_QA_AUTHORIZE("取消QA授权"),
        OPS_AUTHORIZE("OPS授权"),
        CALCEL_OPS_AUTHORIZE("取消OPS授权"),
        CALCEL_ALL_AUTHORIZE("取消所有授权"),
        START_OGG("启动OGG"),
        STOP_OGG("停止OGG");

        private String desc;

        OperateType(String desc) {
            this.desc = desc;
        }


        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }

    public static void operateLog(LoginUser userInfo, OperateType type) {
        String log = createLogStr(userInfo, type);
        writeLog(log);
    }

    private static String createLogStr(LoginUser userInfo, OperateType type) {
        StringBuffer log = new StringBuffer();

        log.append(" 用户名:(").append(userInfo.getUserName()).append(") 角色:(|");
        for (RoleInfo roleInfo : userInfo.getUserRole()) {
            log.append(roleInfo.getRole_name()).append("|");
        }
        log.append(") IP:(").append(userInfo.getLogin_ip()).append(") 操作:").append(type).append("(").append(type.getDesc()).append(")");
        return log.toString();
    }

    private static synchronized void writeLog(String log) {
        String[] param = new String[4];
        param[0] = "bash";
        param[1] = Constants.SHELL_PATH + "shell/beetle_write_log.sh";
        param[2] = getLogFilePath();
        param[3] = log;
        ShellRunUtil.runShell(param);
    }

    private static String getLogFilePath() {
        StringBuffer path = new StringBuffer();
        path.append(Constants.BASE_DIR).append("/logs/log-").append(DateUtil.getCurDateStr("yyyyMMdd")).append(".log");
        return path.toString();
    }
}
